/*
 *
 * @ProjectName:    my_umi_app
 * @Package:
 * @ClassName:      useOnOutsideClick
 * @Description:    JSX文件
 * @Author:         SuPeiSen
 * @CreateDate:     2021/1/20 4:44 下午
 * @UpdateDate:     2021/1/20 4:44 下午
 * @UpdateRemark:   更新说明：
 * @Version:        1.0
 */

import { useEffect, useRef } from 'react';
import { findDOMNode } from 'react-dom';

export const useOnOutsideClick = function <T extends HTMLElement>(
  handleOutsideClick: Function,
) {
  const innerBorderRef = useRef<T>(null);

  const onClick = (event: any) => {
    if (innerBorderRef.current !== null && innerBorderRef.current) {
      const result = findDOMNode(innerBorderRef.current)?.contains(
        event.target,
      );
      if (!result) {
        handleOutsideClick();
      }
    }
  };

  useEffect(() => {
    document.body.addEventListener('click', onClick, true);
    return () => {
      document.body.removeEventListener('click', onClick, true);
    };
  }, []);

  return { innerBorderRef };
};
